package com.jkrohn.io2011.AccessibleYouTube;

import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.TextView;

public class AccessibleYouTube extends Activity {
	
	static ListView lv;
	static YouTubeResult current;
	static ArrayList<YouTubeResult> results;
	static String lastSearched;
	
	//public static final String PREFS_NAME = "YouTubeCaptionRatings";
	
	SharedPreferences settings;
	
	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		// setContentView(R.layout.main);
		setContentView(R.layout.search);
		lv = (ListView) findViewById(R.id.listViewSearchResults);
		//used for rating storage
		settings = getPreferences(0);
	}

	public void searchButtonPress(View view) {
		InputMethodManager imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
		imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
		// System.out.println("button pressed...");
		String search = ((EditText) findViewById(R.id.searchText)).getText().toString();
		lastSearched = search;
		if (search.replace(" ", "").length() == 0) {
			return;
		}
		// System.out.println("Box=" + search);
		setContentView(R.layout.results);
		((TextView) findViewById(R.id.textViewSearchResultTitle))
				.setText("Captioned search results for " + search);
		ArrayList<YouTubeResult> ytResults = searchYoutube(search);
		int size = ytResults.size();
		//lv.setAdapter(new ArrayAdapter<String>(this, R.layout., COUNTRIES))
		ArrayList<String> ytResultsStr = new ArrayList<String>();
		for(YouTubeResult result : ytResults) {
			ytResultsStr.add(result.toString());
		}
		results = ytResults;
		//ListAdapter la = ;
		((ListView) findViewById(R.id.listViewSearchResults)).setAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, ytResultsStr));
		((ListView) findViewById(R.id.listViewSearchResults)).requestFocus();
		((ListView) findViewById(R.id.listViewSearchResults)).setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
				// TODO Auto-generated method stub
				listViewClick(arg1, arg2);
			}
			
			});
	}
	
	public void listViewClick(View view, int pressed) {
		current = results.get(pressed);
		displayVideoPage();
	}
	
	public void displayVideoPage() {
		setContentView(R.layout.result);
		((TextView) findViewById(R.id.textViewVideoTitle))
		.setText(current.title);
		((TextView) findViewById(R.id.textViewCaptionRating))
		.setText(current.captionRatingString());
		((TextView) findViewById(R.id.textViewVideoAuthor))
		.setText("Author: " + current.author);
		findViewById(R.id.buttonWatchVideo).requestFocus();
	}
	
	public void watchVideo(View view) {
		Intent i = new Intent(Intent.ACTION_VIEW);
		i.setData(Uri.parse(current.url));
		startActivity(i);
	}
	
	public void ratePressed(View view) {
		setContentView(R.layout.ratecaption);
		((Button)findViewById(R.id.buttonRate3)).requestFocus();
	}
	
	
	//note: HORRIBLE way to do it, but fast
	
	public void rate1(View view) {
		rate(1);
	}
	
	public void rate2(View view) {
		rate(2);
	}
	
	public void rate3(View view) {
		rate(3);
	}
	
	public void rate4(View view) {
		rate(4);
	}
	
	public void rateFive(View view) {
		rate(5);
	}
	
	public void rate(int value) {
		SharedPreferences.Editor editor = settings.edit();
		editor.putInt(current.url, value);
		editor.commit();
		current.rating = value;
		displayVideoPage();
	}

	public ArrayList<YouTubeResult> searchYoutube(String search) {
		// adopted from
		// http://stackoverflow.com/questions/4023058/android-trying-to-get-data-from-youtube-api
		URL url;
		// http://gdata.youtube.com/feeds/mobile/videos/-/{http://gdata.youtube.com/schemas/2007/keywords.cat}google/{http://gdata.youtube.com/schemas/2007/keywords.cat}developers
		//ugh, normally would use regular expression, but in big time crunch
		String[] searchWords = search.split(" ");
		String searchUrl = "http://gdata.youtube.com/feeds/mobile/videos/-";// /{http://gdata.youtube.com/schemas/2007/keywords.cat}
		searchUrl = "http://gdata.youtube.com/feeds/api/videos?q=" + searchWords[0];
		//http://gdata.youtube.com/feeds/api/videos?q=football+-soccer&orderby=relevance&start-index=11&max-results=10&v=2
		boolean first = true;
		for (String s : searchWords) {
			if(first) {
				first = false;
			}
			else {
				searchUrl += "+" + s;
			}
			//searchUrl += "/{http://gdata.youtube.com/schemas/2007/keywords.cat}" + s;
			
		}
		//searchUrl += "&caption&orderby=relevance&start-index=1&max-results=100&v=2";
		searchUrl += "&caption&orderby=relevance&v=2";
		//searchUrl = "http://gdata.youtube.com/feeds/api/standardfeeds/recently_featured?&start-index=1&max-results=15&v=2";
		System.out.println(searchUrl);
		ArrayList<YouTubeResult> output = new ArrayList<YouTubeResult>();
		try {
			url = new URL(searchUrl);

			URLConnection connection;
			connection = url.openConnection();

			HttpURLConnection httpConnection = (HttpURLConnection) connection;

			int responseCode = httpConnection.getResponseCode();
			System.out.println("Response code:" + responseCode);
			if (responseCode == HttpURLConnection.HTTP_OK) {
				
				InputStream in = httpConnection.getInputStream();

				DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
				DocumentBuilder db = dbf.newDocumentBuilder();

				// Parse the earthquake feed.
				Document dom = db.parse(in);
				Element docEle = dom.getDocumentElement();

				// Get a list of each earthquake entry.
				NodeList nl = docEle.getElementsByTagName("entry");
				if (nl != null && nl.getLength() > 0) {
					final int length = nl.getLength();
					for (int i = 0; i < length; i++) {
						Element entry = (Element) nl.item(i);
						
						Element title = (Element) entry.getElementsByTagName("title").item(0);
						Element id = (Element) entry.getElementsByTagName("id").item(0);
						Element author = (Element) entry.getElementsByTagName("author").item(0);
						author = (Element) entry.getElementsByTagName("name").item(0);
						
						String titleStr = title.getFirstChild().getNodeValue();
						String authorStr = author.getFirstChild().getNodeValue();
						//tag:youtube.com,2008:video:2TCLeIyBwoU
						String videoUrl = "http://www.youtube.com/watch?v=" + id.getFirstChild().getNodeValue().split(":video:")[1];
						int rating = settings.getInt(videoUrl, -1);
						YouTubeResult ytr = new YouTubeResult(titleStr, videoUrl, authorStr, rating);
						//ytr.title = titleStr;
						//ytr.url = videoUrl;
						//ytr.author = authorStr;
						//System.out.println(entry.toString());
						output.add(ytr);
						//System.out.println(ytr);
						// VideoCell cell = new VideoCell(titleStr);

						// Process a newly found earthquake
						// addVideoCellToArray(cell);
					}
				}
			}
		} catch (MalformedURLException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} catch (ParserConfigurationException e) {
			e.printStackTrace();
		} catch (SAXException e) {
			e.printStackTrace();
		} finally {
		}
		return output;
	}

}